package cn.edu.ncu.housinghub.advice;


import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Set;

@Aspect
@Component
public class IdentityVerification {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

//    @Before("execution()")
    public void checkIdentityVerification(JoinPoint joinPoint) {
        // 1. 获取当前请求的token
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("info");

        if (token == null || token.isEmpty()) {
            throw new BusinessException(ErrorCodeConstant.TOKEN_MISSING);
        }

        // 2. 从Redis中查询token对应的用户信息
        Set<String> keys = redisTemplate.keys(SystemConstant.REDIS_TOKEN_PREFIX_USER.getStringValue() + "*:" + token);

        if (keys == null || keys.isEmpty()) {
            throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
        }

        String redisKey = keys.iterator().next();

        // 3. 从Redis中获取存储的User对象（loginUser）
        User loginUser = (User) redisTemplate.opsForValue().get(redisKey);

        if (loginUser == null) {
            throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
        }

        // 4 验证用户是否已实名认证
        if (!loginUser.getIsIdentityVerified()) { // 假设User类有isIdentityVerified()方法
            throw new BusinessException(ErrorCodeConstant.USER_DONT_VERIFIED);
        }
    }
}
